﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Net.Sockets;
using System.Net;
using System.Runtime.InteropServices;
using MSXML2;

namespace FanTong
{
    public partial class MainForm : Form
    {
        string oldIDs;
        string newIDs;
        string HTML; //浏览器HTML内容
        public bool isLoading = false;
        public int index = 0;
        int msgFlg; //装载消息标志
        string userName = ""; //用户名
        string lastUserName = "";
        string password = ""; //用户密码
        int updateInterval = 3;//更新间隔
        bool isLoad = true;
        bool autoLogin; //自动登录
        int freshtime; //更新频率
        string fontname; //字体名
        string fontsize; //字体大小
        string fontbold; //字体是否粗写
        string[] strFriendsNameArr;
        string[] strFriendsIdArr;
        bool isPrintFriendBegin;
        bool isPrintFriendFinish;

        string[] strFollowsIdArr;
        string[] strFollowsNameArr;
        string[] strFollowsImageArr;

        int MatchedPrivateIndex;
        string PrivateMsgRecipientId;

        string sErrorMsg;
        public OperationINI.rwini ini = new OperationINI.rwini(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName) + "\\Config.ini");
        private Random rnd = new Random(DateTime.Now.Millisecond);
        public Microsoft.WindowsCE.Forms.InputPanel inputPanel = new Microsoft.WindowsCE.Forms.InputPanel();
        public MainForm()
        {
            InitializeComponent();
        }

        private void btn_White_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.White;
        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            ini.IniWriteValue("config", "isShow", "0");
            ini.IniWriteValue("UserConfig", "LastUserName", userName);
            Application.Exit();
        }

        private void txtName_GotFocus(object sender, EventArgs e)
        {
            inputPanel.Enabled = true;
        }
        private void txtName_LostFocus(object sender, EventArgs e)
        {
            inputPanel.Enabled = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //this.panMenu.BackColor = Color.FromArgb(0, 184, 229);
            //this.picHome.BackColor = Color.FromArgb(0, 184, 229);
            //this.labHome.BackColor = Color.FromArgb(0, 184, 229);
            //this.picPrivateLetter.BackColor = Color.FromArgb(0, 184, 229);
            //this.labPrivateLetter.BackColor = Color.FromArgb(0, 184, 229);
            //this.picFriend.BackColor = Color.FromArgb(0, 184, 229);
            //this.labFriend.BackColor = Color.FromArgb(0, 184, 229);
            //this.picSearch.BackColor = Color.FromArgb(0, 184, 229);
            //this.labSearch.BackColor = Color.FromArgb(0, 184, 229);
            userName = ini.IniReadValue("UserConfig", "UserName");
            password = new EncryptionDecryption().decode(ini.IniReadValue("UserConfig", "UserPassWord"));
            lastUserName = ini.IniReadValue("UserConfig", "LastUserName");
            updateInterval = int.Parse(ini.IniReadValue("LoadMessage", "updateInterval"));
            msgFlg = 1;
            isLoad = true;
            picHome_Click(sender, e);
            loadTime.Enabled = true;
            loadTime.Interval = updateInterval * 60 * 1000 + 100;
        }

        private void MainForm_Paint(object sender, PaintEventArgs e)
        {
            //picTitle.SendToBack();
            //ImageAttributes imgAttribs = new ImageAttributes();
            //imgAttribs.SetColorKey(Color.FromArgb(255, 255, 255), Color.FromArgb(255, 255, 255));

            //Graphics g = this.CreateGraphics();
            //g.DrawImage(picPost.Image, new Rectangle(3, 3, picPost.Image.Width, picPost.Image.Height), 0, 0, picPost.Image.Width, picPost.Image.Height, GraphicsUnit.Pixel, imgAttribs);
        }

        private void picPost_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("asdfasdf", "Test");
            panPostMsg.Top = 37;
            panPostMsg.Left = 90;
            panPostMsg.Width = 310;
            panPostMsg.Height = 182;
            panPostMsg.Visible = true;
            txtPostText.Focus();
            labError.Visible = false;
        }

        private void ClearPicImage()
        {
            picHome.Image = imgMenuButtonBG.Images[1];
            picPrivateLetter.Image = imgMenuButtonBG.Images[1];
            picFriend.Image = imgMenuButtonBG.Images[1];
            picSearch.Image = imgMenuButtonBG.Images[1];
        }

        private void picHome_Paint(object sender, PaintEventArgs e)
        {
            Label L = labHome;
            L.Visible = false;
            int left = 12;
            int top = 9;
            e.Graphics.DrawString(L.Text, L.Font, new SolidBrush(L.ForeColor), left, top);
        }

        private void picPrivateLetter_Paint(object sender, PaintEventArgs e)
        {
            Label L = labPrivateLetter;
            L.Visible = false;
            //int left = L.Left - picHome.Left;
            //int top = L.Top - picHome.Top;
            int left = 12;
            int top = 9;
            e.Graphics.DrawString(L.Text, L.Font, new SolidBrush(L.ForeColor), left, top);
        }

        private void picFriend_Paint(object sender, PaintEventArgs e)
        {
            Label L = labFriend;
            L.Visible = false;
            int left = 12;
            int top = 9;
            e.Graphics.DrawString(L.Text, L.Font, new SolidBrush(L.ForeColor), left, top);
        }

        private void picSearch_Paint(object sender, PaintEventArgs e)
        {
            Label L = labSearch;
            L.Visible = false;
            int left = 12;
            int top = 9;
            e.Graphics.DrawString(L.Text, L.Font, new SolidBrush(L.ForeColor), left, top);
        }
        private void picHome_Click(object sender, EventArgs e)
        {
            ClearPicImage();
            picHome.Image = imgMenuButtonBG.Images[0];
            msgFlg = 1;
            DateTime nowdate = DateTime.Now;
            string lastLoadDate = ini.IniReadValue("LoadMessage", "lastUsertimelineTime");
            //ini.IniWriteValue("LoadMessage", "updateInterval", "3");
            int isFlg = int.Parse(ini.IniReadValue("LoadMessage", "msgFlg"));

            if ((sErrorMsg != null && sErrorMsg.Length > 0) || isLoad || lastUserName != userName)
            {
                isLoad = false;
                ini.IniWriteValue("LoadMessage", "lastUsertimelineTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/statuses/user_timeline.xml?id=" + userName + "&count=20", true, 1);
            }
            else if (string.IsNullOrEmpty(lastLoadDate))
            {
                ini.IniWriteValue("LoadMessage", "lastUsertimelineTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/statuses/user_timeline.xml?id=" + userName + "&count=20", true, 1);
            }
            else
            {
                TimeSpan Interval = nowdate - DateTime.Parse(lastLoadDate);
                if (Interval.TotalMinutes >= updateInterval && isFlg != msgFlg)
                {
                    ini.IniWriteValue("LoadMessage", "lastUsertimelineTime", nowdate.ToString());
                    UpdateMsgList("http://api.fanfou.com/statuses/user_timeline.xml?id=" + userName + "&count=20", true, 1);
                }
                else
                {
                    ChangeText("");
                }
            }
        }
        private void picPrivateLetter_Click(object sender, EventArgs e)
        {
            ClearPicImage();
            picPrivateLetter.Image = imgMenuButtonBG.Images[0];
            msgFlg = 4;
            DateTime nowdate = DateTime.Now;
            string lastLoadDate = ini.IniReadValue("LoadMessage", "lastInboxTime");
            //ini.IniWriteValue("LoadMessage", "updateInterval", "3");
            int isFlg = int.Parse(ini.IniReadValue("LoadMessage", "msgFlg"));
            if ((sErrorMsg != null && sErrorMsg.Length > 0) || isLoad || lastUserName != userName)
            {
                isLoad = false;
                ini.IniWriteValue("LoadMessage", "lastInboxTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/private_messages/inbox.xml?count=20", true, 4);
            }
            else if (string.IsNullOrEmpty(lastLoadDate))
            {
                ini.IniWriteValue("LoadMessage", "lastInboxTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/private_messages/inbox.xml?count=20", true, 4);
            }
            else
            {
                TimeSpan Interval = nowdate - DateTime.Parse(lastLoadDate);
                if (Interval.TotalMinutes >= updateInterval && isFlg != msgFlg)
                {
                    ini.IniWriteValue("LoadMessage", "lastInboxTime", nowdate.ToString());
                    UpdateMsgList("http://api.fanfou.com/private_messages/inbox.xml?count=20", true, 4);
                }
                else
                {
                    ChangeText("");
                }
            }
        }

        private void picFriend_Click(object sender, EventArgs e)
        {
            ClearPicImage();
            picFriend.Image = imgMenuButtonBG.Images[0];
            msgFlg = 2;
            DateTime nowdate = DateTime.Now;
            string lastLoadDate = ini.IniReadValue("LoadMessage", "lastFriendstimelineTime");
            //ini.IniWriteValue("LoadMessage", "updateInterval", "3");
            int isFlg = int.Parse(ini.IniReadValue("LoadMessage", "msgFlg"));
            if ((sErrorMsg != null && sErrorMsg.Length > 0) || isLoad || lastUserName != userName)
            {
                isLoad = false;
                ini.IniWriteValue("LoadMessage", "lastFriendstimelineTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/statuses/friends_timeline.xml?id=" + userName + "&count=20", false, 2);
            }
            else if (string.IsNullOrEmpty(lastLoadDate))
            {
                ini.IniWriteValue("LoadMessage", "lastFriendstimelineTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/statuses/friends_timeline.xml?id=" + userName + "&count=20", false, 2);
            }
            else
            {
                TimeSpan Interval = nowdate - DateTime.Parse(lastLoadDate);
                if (Interval.TotalMinutes >= updateInterval && isFlg != msgFlg)
                {
                    ini.IniWriteValue("LoadMessage", "lastFriendstimelineTime", nowdate.ToString());
                    UpdateMsgList("http://api.fanfou.com/statuses/friends_timeline.xml?id=" + userName + "&count=20", false, 2);
                }
                else
                {
                    ChangeText("");
                }
            }
        }

        private void picSearch_Click(object sender, EventArgs e)
        {
            ClearPicImage();
            picSearch.Image = imgMenuButtonBG.Images[0];

            msgFlg = 5;
            DateTime nowdate = DateTime.Now;
            string lastLoadDate = ini.IniReadValue("LoadMessage", "lastPublictimelineTime");
            //ini.IniWriteValue("LoadMessage", "updateInterval", "3");
            int isFlg = int.Parse(ini.IniReadValue("LoadMessage", "msgFlg"));
            if ((sErrorMsg != null && sErrorMsg.Length > 0) || isLoad || lastUserName != userName)
            {
                isLoad = false;
                ini.IniWriteValue("LoadMessage", "lastPublictimelineTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/statuses/public_timeline.xml?id=" + userName + "&count=20", false, 5);
            }
            else if (string.IsNullOrEmpty(lastLoadDate))
            {
                ini.IniWriteValue("LoadMessage", "lastPublictimelineTime", nowdate.ToString());
                UpdateMsgList("http://api.fanfou.com/statuses/public_timeline.xml?id=" + userName + "&count=20", false, 5);
            }
            else
            {
                TimeSpan Interval = nowdate - DateTime.Parse(lastLoadDate);
                if (Interval.TotalMinutes >= updateInterval && isFlg != msgFlg)
                {
                    ini.IniWriteValue("LoadMessage", "lastPublictimelineTime", nowdate.ToString());
                    UpdateMsgList("http://api.fanfou.com/statuses/public_timeline.xml?id=" + userName + "&count=20", false, 5);
                }
                else
                {
                    ChangeText("");
                }
            }
        }

        //启动更新消息列表线程
        private void UpdateMsgList(string Url, bool UseAuth, int UserMsgFlg)
        {
            ini.IniWriteValue("LoadMessage", "msgFlg", UserMsgFlg.ToString());
            showPageLoading();
            UpdateMsgList mylist = new UpdateMsgList();
            System.Threading.ThreadStart myThreadStart = default(System.Threading.ThreadStart);
            System.Threading.Thread myThread = default(System.Threading.Thread);
            mylist.setURL = Url;
            mylist.setUseAuth = UseAuth;
            mylist.setUserMsgFlg = UserMsgFlg;
            mylist.setUserName = userName;
            mylist.setPassword = password;
            mylist.setFollowsIdArr = strFollowsIdArr;
            mylist.setFollowsImageArr = strFollowsImageArr;

            mylist.UpdateMsgListComplete += updateBrowser;

            myThreadStart = new System.Threading.ThreadStart(mylist.UpdateMsgList_Renamed);
            myThread = new System.Threading.Thread(myThreadStart);
            myThread.Start();
        }

        //更新消息列表线程完成
        private delegate void MyInvokeDelegate(string name);
        private void updateBrowser(string innerHTML, string IDs, string[] ReplyMsgsIdArr2, string[] ReplyMsgsNameArr2, int[] ReplyMsgsFlagArr2, string[] ReplyMsgsContentArr2, string ErrorMsg)
        {
            newIDs = IDs;
            HTML = innerHTML;
            //if ((string.Compare(newIDs, oldIDs) != 0))
            //{
            //    oldIDs = newIDs;
            //}
            //if ((ErrorMsg.Length > 0))
            //{

            //    //StatusLabel.Text = "不能连接到服务器！";
            //    //NotifyForm.syncReplyMsgs(ReplyMsgsIdArr2, ReplyMsgsNameArr2, ReplyMsgsFlagArr2, ReplyMsgsContentArr2)
            //}
            this.Invoke(new MyInvokeDelegate(this.ChangeText), innerHTML);
        }
        private void showPageLoading()
        {
            panLoding.Top = 37;
            panLoding.Left = 0;
            panLoding.Width = 480;
            panLoding.Height = 602;
            panLoding.Visible = true;
            isLoading = true;
            timer1.Enabled = true;
        }
        private void hidePageLoading()
        {
            panLoding.Visible = false;
            isLoading = false;
            timer1.Enabled = false;
        }
        private void WriteFile(string filename, byte[] str)
        {
            FileStream TextFile = File.Open(filename, FileMode.Create);
            TextFile.Write(str, 0, str.Length);
            TextFile.Close();
        }
        private void WriteFile(string filename, string str)
        {
            FileStream TextFile = File.Open(filename, FileMode.Create);
            StreamWriter sw = new StreamWriter(TextFile, System.Text.Encoding.GetEncoding("gb2312"));
            sw.Write(str);
            sw.Close();
            TextFile.Close();
        }
        private void ChangeText(string HTML)
        {
            string filenames = "style.html";
            switch ((msgFlg))
            {
                case 1:
                    filenames = "user_timeline.html";
                    break;
                case 2:
                    filenames = "friends_timeline.html";
                    break;
                case 3:
                    filenames = "friends_timeline.html";
                    break;
                case 4:
                    filenames = "inbox.html";
                    break;
                case 5:
                    filenames = "public_timeline.html";
                    break;
            }
            if (HTML.Length > 0)
            {
                WriteFile(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName) + "\\Html\\" + filenames, HTML);
            }
            Uri urls = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName) + "\\Html\\" + filenames);
            webBrowser1.Navigate(urls);
            //this.webBrowser1.DocumentText = HTML;
            hidePageLoading();
        }

        private void picexit_MouseDown(object sender, MouseEventArgs e)
        {
            //picexit.Image
            picexit.Image = imgbuttons.Images[1];
        }

        private void picexit_MouseUp(object sender, MouseEventArgs e)
        {
            picexit.Image = imgbuttons.Images[0];
        }

        private void picexit_Paint(object sender, PaintEventArgs e)
        {
            Label L = labExit;
            L.Visible = false;
            int left = L.Left - picexit.Left;
            int top = L.Top - picexit.Top;
            //int left = 12;
            //int top = 9;
            e.Graphics.DrawString(L.Text, L.Font, new SolidBrush(L.ForeColor), left, top);
        }
        public void loadingSetImg(int indexs)
        {
            picloding.Image = imgloadingList.Images[indexs];
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (index == 5)
                index = 0;
            else
                index++;
            loadingSetImg(index);
        }

        private void linlabCancel_Click(object sender, EventArgs e)
        {
            panPostMsg.Visible = false;
            inputPanel.Enabled = false;
            webBrowser1.Focus();
        }

        private void txtPostText_GotFocus(object sender, EventArgs e)
        {
            inputPanel.Enabled = true;
        }

        private void txtPostText_LostFocus(object sender, EventArgs e)
        {
            inputPanel.Enabled = false;
        }
        private string Post(string Msg)
        {

            //Create the xmlhttp object
            XMLHTTPClass xmlhttp = new XMLHTTPClass();
            string ErrorMsg = null;
            ErrorMsg = "";

            try
            {
                //Open a connection and send a request to the server in the form of an XML fragment
                xmlhttp.open("POST", "http://api.fanfou.com/statuses/update.xml", false, userName, password);
                xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xmlhttp.setRequestHeader("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(userName + ":" + password)));
                xmlhttp.send("source=M8FanTong&status=" + Msg);
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.Message;
            }
            return ErrorMsg;
        }
        private void linlabPostMsg_Click(object sender, EventArgs e)
        {
            inputPanel.Enabled = false;
            if ((txtPostText.Text.Length > 0))
            {
                showPageLoading();
                string ErrorMsg = null;
                //if (msgFlg == 4)
                //{
                //    ErrorMsg = PostPrivateMsg(PrivateMsgRecipientId, txtPostText.Text);
                //}
                //else
                //{                
                ErrorMsg = Post(txtPostText.Text);
                //}

                if ((ErrorMsg.Length > 0))
                {
                    hidePageLoading();
                    labError.Text = "不能连接到服务器，发送失败！";
                    labError.Visible = true;
                    inputPanel.Enabled = true;
                }
                else
                {
                    txtPostText.Text = null;
                    isLoad = true;
                    switch ((msgFlg))
                    {
                        case 1:
                            this.picHome_Click(sender, e);
                            break;
                        case 2:
                            this.picFriend_Click(sender, e);
                            break;
                        case 3:
                            this.picFriend_Click(sender, e);
                            break;
                        case 4:
                            this.picPrivateLetter_Click(sender, e);
                            break;
                        case 5:
                            this.picSearch_Click(sender, e);
                            break;
                    }
                    //switch ((msgFlg))
                    //{
                    //    case 1:
                    //        UpdateMsgList("http://api.fanfou.com/statuses/user_timeline.xml?id=" + userName + "&count=20", true, 1);
                    //        break;
                    //    case 2:
                    //        UpdateMsgList("http://api.fanfou.com/statuses/friends_timeline.xml?id=" + userName + "&count=20", false, 2);
                    //        break;
                    //    case 3:
                    //        break;
                    //    case 4:
                    //        UpdateMsgList("http://api.fanfou.com/private_messages/inbox.xml?count=10", true, 4);
                    //        break;
                    //    case 5:
                    //        UpdateMsgList("http://api.fanfou.com/statuses/friends_timeline.xml?id=" + userName + "&count=20", false, 2);
                    //        msgFlg = 2;
                    //        break;
                    //}
                    if (msgFlg == 4)
                    {
                        labError.Text = "私信发送成功！";
                        labError.Visible = true;
                    }
                    else
                    {
                        labError.Text = "消息发送成功！";
                        labError.Visible = true;
                    }
                }

                txtPostText.Focus();
            }
            else
            {
                labError.Text = "消息不能为空！";
                labError.Visible = true;
                inputPanel.Enabled = true;
            }
        }

        private void MainForm_Deactivate(object sender, EventArgs e)
        {
            //ini.IniWriteValue("UserConfig", "LastUserName", userName);
            //Application.Exit();
        }

        private void loadTime_Tick(object sender, EventArgs e)
        {
            switch ((msgFlg))
            {
                case 1:
                    this.picHome_Click(sender, e);
                    break;
                case 2:
                    this.picFriend_Click(sender, e);
                    break;
                case 3:
                    this.picFriend_Click(sender, e);
                    break;
                case 4:
                    this.picPrivateLetter_Click(sender, e);
                    break;
                case 5:
                    this.picSearch_Click(sender, e);
                    break;
            }
        }
        public void Reply(string userName)
        {
            txtPostText.Text = "@" + userName;
            panPostMsg.Top = 37;
            panPostMsg.Left = 90;
            panPostMsg.Width = 310;
            panPostMsg.Height = 182;
            panPostMsg.Visible = true;
            txtPostText.Focus();
            labError.Visible = false;
        }
    }

}